package com.itheima.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录拦截, 验证登录是否过期
 */
@Component
public class LoginFilter implements Filter {


    @Autowired
    private JedisPool jedisPool;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        Cookie[] cookies = req.getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("login_member_telephone".equals(cookie.getName())) {
                    String telephone = cookie.getValue();
                    String member = jedisPool.getResource().get(telephone);
                    if (member != null && member.length() > 0) {
                        chain.doFilter(req, resp);
                        return;
                    }
                }
            }
        }
        resp.sendRedirect("/login.html");
    }

    @Override
    public void destroy() {

    }
}
